package org.zxyj.system.server.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zxyj.core.service.AbstractBaseServiceImpl;
import org.zxyj.system.dao.IUserDao;
import org.zxyj.system.dao.IUserRoleDao;
import org.zxyj.system.domain.User;
import org.zxyj.system.domain.UserRole;
import org.zxyj.system.server.IUserService;

/**
 * @author zhaoyong
 * @version 2016年2月26日
 */
@Service
public class UserServiceImpl extends AbstractBaseServiceImpl<IUserDao, User>implements IUserService {

	@Autowired
	private IUserRoleDao userRoleDao;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void persistentEntity(User user) {
		super.persistentEntity(user);

		// 持久化处理用户角色
		this.persistentUserRoles(user);
	}

	/**
	 * 持久化处理用户角色
	 * 
	 * @param role
	 */
	private void persistentUserRoles(User user) {
		if (null != user && null != user.getId()) {
			// 删除该角色下所有的权限
			Map<String, Object> criteria = new HashMap<String, Object>();
			criteria.put("user", user);
			userRoleDao.delete(criteria);

			List<UserRole> userRoles = user.getUserRoles();
			if (!CollectionUtils.isEmpty(userRoles)) {
				List<UserRole> tempUserRoles = new ArrayList<UserRole>();
				for (UserRole userRole : userRoles) {
					if (userRole.getRole() == null) {
						continue;
					}
					userRole.setUser(user);
					tempUserRoles.add(userRole);
				}
				userRoleDao.batchInsert(tempUserRoles);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteEntity(Map<String, Object> criteria) {
		logger.debug("deleting user from DB, param: criteria[{}]", criteria);

		if (!MapUtils.isEmpty(criteria)) {
			// 级联删除用户角色
			List<User> users = this.listEntities(criteria);
			if (!CollectionUtils.isEmpty(users)) {
				Map<String, Object> deleteCriteria = new HashMap<String, Object>();
				deleteCriteria.put("users", users);
				userRoleDao.delete(deleteCriteria);

				dao.delete(criteria);
			}
		}
	}

}